'use strict'

let sceneMgr = require('../core/sceneMgr')
let playerDao = require('../dao').PlayerDao
let tradeDao = require('../dao').TradeDao
let templateConfig = require('../../config/templateConfig')
let ItemComponent = require('../component/itemComponent')
let attackHandle = require('../core/attackHandle')
let adventure = require('../core/adventure')
let fieldBossComponent = require('../component/fieldBossComponent')
let arenaHandle = require('../component/arenaComponent')
let route = require('./route')
let pushMsg = require('./pushMsg')
let playerSessionMgr = require('../core/playerSessionMgr')
let mailDao = require('../dao').MailDao
let PlayerModel = require('../dao/model').Player
let trialHandle = require('../component/trialComponent')
let guardComponent = require('../component/guardComponent')
let utils = require('../utils/utils')
let gateHandle = require('./gateHandle')
let createPlayerHandle = require('../core/createPlayerHandle')
let PlayerComponent = require('../component/playerComponent')
let skillHandle = require('../core/skillHandle')

//角色登陆
route.setNotLogin('playerLogin', function(msg, next) {
  let userId = msg.userId
    //判断角色是否存在
  playerDao.getPlayerByQuery({
    userId: userId
  }, function(err, res) {
    if (err || !res) {
      next(1)
      return
    }

    let player = new PlayerComponent(res)
    player.initPlayer()
    playerSessionMgr.bind(player._id, player)
    if (player.basicInfo.mapIndex === 1 || player.basicInfo.mapIndex === 2) {
      player.basicInfo.stamina = player.fightAttri.maxStamina
      player.fightAttri.hp = player.fightAttri.maxHp
    }
    player.isFirstLoginEveryDay()
    next({
      error: 0,
      _id: player._id,
      basicInfo: player.basicInfo,
      name: player.name
    })
    return
  })
})

//新建角色
route.setNotLogin('createPlayer', function(msg, next) {
  if (!msg.name) {
    next(1)
    return
  }
  let name = msg.name + ''
  if (name.length < 1 || name.length > 6) {
    next(1)
    return
  }
  let token = msg.token
  let userId = msg.userId
  let str = msg.str,
    con = msg.con,
    agile = msg.agile,
    wisdom = msg.wisdom
  let re = /^[0-9]{1}$/
  if (!re.test(str) || !re.test(con) || !re.test(agile) || !re.test(wisdom)) {
    next(2)
    return
  }
  str = parseInt(str)
  con = parseInt(con)
  agile = parseInt(agile)
  wisdom = parseInt(wisdom)
  let total = str + con + agile + wisdom

  if (templateConfig.total[100001].basicAttri.attriPoint !== total) {
    next(3)
    return
  }
  if (str > 5 || con > 5 || agile > 5 || wisdom > 5) {
    next(4)
    return
  }

  //判断角色是否已经存在
  playerDao.getPlayerByQuery({
    "$or": [{
      userId: userId
    }, {
      name: name
    }]
  }, function(err, res) {
    if (err || res) { //角色已经存在
      next(5)
      return
    }
    createPlayerHandle.create({
      name: name,
      userId: userId,
      templateId: 100001,
      str: str,
      con: con,
      agile: agile,
      wisdom: wisdom
    }, function() {
      next(0)
    })
  })

})

//获取背物品道具名称
route.set('getPropName', function(player, msg, next) {
  next({
    error: 0,
    propName: templateConfig.propName
  })
})

//装备武器
route.set('equip', function(player, msg, next) {
  let pos = msg.pos
  let equipment = player.bag.items[pos]
  if (!equipment) {
    next(1)
    return
  }
  pos = parseInt(pos)
    //判断是不是武器
  if (equipment.type < 50) {
    next(2)
    return
  }
  //弓510000弩520000剑530000刀540000法杖550000
  //魂器600000衣服610000手套620000鞋子630000头盔640000戒指650000
  let equipmentInfo
  let type = Math.floor(equipment.templateId / 10000)
  if (type === 51 || type === 52 || type === 53 || type === 54 || type === 55) {
    equipmentInfo = player.equipments.weapon
    player.equipments.weapon = equipment
  } else if (type === 60) {
    equipmentInfo = player.equipments.soul
    player.equipments.soul = equipment
  } else if (type === 61) {
    equipmentInfo = player.equipments.body
    player.equipments.body = equipment
  } else if (type === 62) {
    equipmentInfo = player.equipments.hand
    player.equipments.hand = equipment
  } else if (type === 63) {
    equipmentInfo = player.equipments.foot
    player.equipments.foot = equipment
  } else if (type === 64) {
    equipmentInfo = player.equipments.head
    player.equipments.head = equipment
  } else if (type === 65) {
    equipmentInfo = player.equipments.ring
    player.equipments.ring = equipment
  } else {
    next(3)
    return
  }
  //移除物品
  player.bag.removeItemByPosition(pos)
  if (equipmentInfo) {
    //添加物品到背包
    let ret = player.bag.addItem(equipmentInfo)
  }
  //重新计算属性
  player.calcAttri()
  next({
    error: 0
  })
})

//卸下武器
route.set('disEquipment', function(player, msg, next) {
  let part = msg.part
    //背包是否有空
  if (player.bag.emptySize === 0) {
    next(1)
    return
  }

  let equipment = player.equipments[part]
  if (!equipment) {
    next(2)
    return
  }
  player.equipments[part] = 0

  //添加物品到背包
  let ret = player.bag.addItem(equipment)
    //重新计算属性
  player.calcAttri()
  next({
    error: 0
  })
})

//获取神秘商店的物品
route.set('getSecretMerchant', function(player, msg, next) {
  if (player.basicInfo.mapIndex !== 4) {
    next(1)
    return
  }
  let secretMerchant = player.secretMerchant
    /*  let secretMapId = player.basicInfo.secretMapId
      let secretMerchantProps = templateConfig.total[290061][secretMapId]*/
  let secretMapId = 280001
  let secretMerchantProps = templateConfig.total[290061][280001]
  Log(secretMerchantProps)
  let nowTime = new Date().getTime()
  if (!secretMerchant[secretMapId]) {
    secretMerchant[secretMapId] = {}
    let props = utils.getRandomArray(6, secretMerchantProps)
    Log(props)
    secretMerchant[secretMapId]['props'] = props
    let nowTime = new Date()
    let hour = Math.floor(nowTime.getHours() / 4) * 4
    nowTime.setHours(hour, 0, 0)
    secretMerchant[secretMapId]['time'] = nowTime.getTime()
  } else if (!secretMerchant[secretMapId]['time'] || nowTime > secretMerchant[secretMapId]['time'] + 14400000) {
    let props = utils.getRandomArray(6, secretMerchantProps)
    Log(props)
    secretMerchant[secretMapId]['props'] = props
    let nowTime = new Date()
    let hour = Math.floor(nowTime.getHours() / 4) * 4
    nowTime.setHours(hour, 0, 0)
    secretMerchant[secretMapId]['time'] = nowTime.getTime()
  }

  next({
    error: 0,
    secretMerchant: secretMerchant[secretMapId],
    time: secretMerchant[secretMapId]['time']
  })
})

//购买神秘商店的物品
route.set('buySecretMerchant', function(player, msg, next) {
  let index = msg.index
  if (player.basicInfo.mapIndex !== 4) {
    next(1)
    return
  }

  let secretMapId = player.basicInfo.secretMapId
  if (!player.secretMerchant[secretMapId]) {
    next(2)
    return
  }
  let propInfo = player.secretMerchant[secretMapId]['props'][index]
  if (!propInfo) {
    next(3)
    return
  }

  let needItemId = propInfo[2]
  let num = player.bag.getTotalNumByItemId(needItemId)
  if (num <= propInfo[3]) {
    next(4)
    return
  }
  player.bag.removeItemByItemId(needItemId, propInfo[3])

  let itemId = propInfo[0]
  let itemNum = propInfo[1]
  let itemComponent = templateConfig.total[itemId].getItemComponent()
  itemComponent.stack = itemNum

  player.adventureBag.push(itemComponent) //添加物品到背包
  player.secretMerchant[secretMapId]['props'][index] = 0
  next({
    error: 0,
    itemId: itemId,
    itemNum: itemNum,
    secretMerchant: player.secretMerchant[secretMapId]
  })
})

//强化身上的装备
route.set('strengthen', function(player, msg, next) {
  let part = msg.part
  let equipment = player.equipments[part]
  if (!equipment) {
    next(1)
    return
  }
  if (equipment.quality <= 1) {
    next(8)
    return
  }
  if (equipment.strengthenLvl >= equipment.lvl) {
    next(7)
    return
  }
  let strengthenConfig = templateConfig.total[440001][equipment.strengthenLvl]
  if (!strengthenConfig) {
    next(2)
    return
  }
  let partConfig = strengthenConfig[part]
  Log(partConfig)
  if (!partConfig) {
    next(3)
    return
  }
  let needProps = partConfig.needProp
    //材料是否足够
  for (let i = 0; i < needProps.length; i++) {
    let itemId = needProps[i][0]
    let itemNum = needProps[i][1]
    let num = player.bag.getTotalNumByItemId(itemId)
    if (num < itemNum) {
      next(4)
      return
    }
  }

  if (partConfig.needMoney) {
    if (player.basicInfo.money < partConfig.needMoney * equipment.quality) {
      next(5)
      return
    }
    player.basicInfo.money -= partConfig.needMoney
  }

  if (partConfig.needGold) {
    if (player.basicInfo.gold < partConfig.needGold * equipment.quality) {
      next(6)
      return
    }
    player.basicInfo.gold -= partConfig.needGold
  }

  //扣除道具
  for (let i = 0; i < needProps.length; i++) {
    let itemId = needProps[i][0]
    let itemNum = needProps[i][1]
    player.bag.removeItemByItemId(itemId, itemNum)
  }

  equipment.strengthenLvl += 1
  player.calcAttri()
  next({
    error: 0
  })
})

//加属性
route.set('attriPointPlus', function(player, msg, next) {
  let re = /^[0-9]*$/
  if (!re.test(msg.str) || !re.test(msg.con) || !re.test(msg.agile) || !re.test(msg.wisdom)) {
    next(1)
    return
  }
  let str = parseInt(msg.str)
  let con = parseInt(msg.con)
  let agile = parseInt(msg.agile)
  let wisdom = parseInt(msg.wisdom)
  let attriPoint = player.basicInfo.attriPoint
  let total = str + con + agile + wisdom
  if (attriPoint < total) {
    next(2)
    return
  }

  player.basicInfo.str += str
  player.basicInfo.con += con
  player.basicInfo.agile += agile
  player.basicInfo.wisdom += wisdom
  player.basicInfo.attriPoint -= total
  player.calcAttri()
  next({
    error: 0
  })
})

//丢弃物品
route.set('discard', function(player, msg, next) {
  let pos = msg.pos
  let item = player.bag.items[pos]
  if (!item) {
    next(1)
    return
  }
  pos = parseInt(pos)
  player.bag.removeItemByPosition(pos)
  next({
    error: 0
  })
})

//物品合成
route.set('itemCompose', function(player, msg, next) {
  let itemId = msg.itemId
  let itemConfig = templateConfig.alchemy[400001][itemId]
  if (!itemConfig) {
    next(1)
    return
  }

  //判断背包是否有空
  if (player.bag.emptySize === 0) {
    next(2)
    return
  }
  let needProp = itemConfig.needProp
    //判断材料是否足够
  for (let i = 0; i < needProp.length; i++) {
    let id = needProp[i][0]
    let itemNum = needProp[i][1]
    let num = player.bag.getTotalNumByItemId(id)
    if (num < itemNum) {
      next(3)
      return
    }
  }
  if (itemConfig.needMoney) { //判断金钱是否足够
    if (player.basicInfo.money < itemConfig.needMoney) {
      next(4)
      return
    }
    player.basicInfo.money -= itemConfig.needMoney
  }

  if (itemConfig.needGold) { //判断金钱是否足够
    if (player.basicInfo.gold < itemConfig.needGold) {
      next(5)
      return
    }
    player.basicInfo.gold -= itemConfig.needGold
  }

  //扣除道具
  for (let i = 0; i < needProp.length; i++) {
    let id = needProp[i][0]
    let itemNum = needProp[i][1]
    player.bag.removeItemByItemId(id, itemNum)
  }

  //扣除金钱
  let itemComponent = templateConfig.total[itemConfig.getItem].getItemComponent()
  //添加物品
  player.bag.addItem(itemComponent)
  next({
    error: 0
  })
})

//报名试炼之所
route.set('joinTrial', function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  let ret = trialHandle.join(player)
  let joinNumber = trialHandle.getJoinNumber()
  next({
    error: 0,
    result: ret,
    joinNumber: joinNumber
  })
})

//获取试炼之所信息
route.set('getTrialInfo', function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  next({
    error: 0,
    trialInfo: player.trialInfo
  })
})

//获取试炼之所信息
route.set('getHasJoinTrial', function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  let ret = trialHandle.hasJoin(player)
  let joinNumber = trialHandle.getJoinNumber()
  next({
    error: 0,
    hasJoin: ret,
    joinNumber: joinNumber
  })
})

//获取所有邮件
route.set('getMails', function(player, msg, next) {
  let re = /^[0-9]*$/
  if (!re.test(msg.page)) {
    next(1)
    return
  }
  let page = parseInt(msg.page)
  mailDao.getMailsByQuerys({
    playerId: player._id
  }, page, 6, function(err, res) {
    next({
      error: 0,
      mails: res,
      isFirst: page === 0,
      isLast: res.length < 7
    })
  })
})

//提取邮箱东西
route.set('extractMail', function(player, msg, next) {
  let mailId = msg.mailId
  mailDao.getMailByQuery({
    _id: mailId
  }, function(err, res) {
    if (err || !res) {
      next(1)
      return
    }
    let con = res
    let items = con.items
    let money = con.money
    let gold = con.gold
    if (items && items.length > 0) {
      let len = items.length
      if (player.bag.emptySize < len) {
        next(2)
        return
      }
      for (let i = 0; i < len; i++) {
        let itemComponent = templateConfig.total[items[i][0]].getItemComponent(items[i][1], items[i][2])
        player.bag.addItem(itemComponent)
      }
    }

    if (money > 0) {
      player.basicInfo.money += money
    }

    if (gold > 0) {
      player.basicInfo.gold += gold
    }

    mailDao.updateMailById(con._id, {
      items: [],
      money: 0,
      gold: 0,
    }, function(err, res) {
      next(0)
      return
    })
  })
})

//删除邮件
route.set('deleteMail', function(player, msg, next) {
  let mailId = msg.mailId
  mailDao.getMailByQuery({
    _id: mailId
  }, function(err, res) {
    if (err || !res) {
      next(1)
      return
    }
    mailDao.removeMailByQuery({
      _id: mailId
    }, function(err, res) {
      next(0)
      return
    })
  })
})

//提取冒险背包物品
route.set('extractABag', function(player, msg, next) {
  let mapIndex = player.basicInfo.mapIndex
  let adventureBag = player.adventureBag
  if (mapIndex !== 1) {
    next(1)
    return
  }
  for (let i = adventureBag.length - 1; i >= 0; i--) {
    let itemComponent = adventureBag[i]
    let ret = player.bag.addItem(itemComponent)

    if (ret === -1) {
      next({
        error: 0,
        result: 1,
      })
      return
    }
    player.adventureBag.pop()
  }
  next({
    error: 0,
    result: 0,
  })
})

//删除冒险背包物品
route.set('deleteABag', function(player, msg, next) {
  let index = msg.index
  if (!player.adventureBag[index]) {
    next(1)
    return
  }
  player.adventureBag.splice(index, 1)
  next({
    error: 0
  })
  return
})

//攻击守护之地boss
route.set('attackFieldBoss', function(player, msg, next) {
  if(player.basicInfo.mapIndex !== 4){
    next(3)
  }
  if (player.fightAttri.hp <= 0) {
    next(1)
    return
  }
  let fightMsg = guardComponent.attackFieldBoss(player, player.basicInfo.sceneId)
  if (fightMsg === -1) {
    next(2)
    return
  }
  next({
    error: 0,
    fightMsg: fightMsg
  })
})

//祭坛复活
route.set('altarRevive', function(player, msg, next) {
  if (player.basicInfo.mapIndex !== 4) {
    next(1)
    return
  }

  if (player.basicInfo.stamina <= 1) {
    next(2)
    return
  }
  player.basicInfo.stamina -= 1
  player.calcAttri()
  player.fightAttri.hp = player.fightAttri.maxHp
  next({
    error: 0
  })
})

//祭坛返回营地
route.set('altarReturnCamp', function(player, msg, next) {
  if (player.basicInfo.mapIndex !== 4) {
    next(1)
    return
  }
  player.basicInfo.mapIndex = 4
  player.basicInfo.sceneId = 260001
  gateHandle.callRemoteFunc('enterScene', {
      sceneId: 260001,
      pId: player._id
    })
    //回到营地,恢复生命和体力
  player.basicInfo.luckyBuff = 0
  player.basicInfo.moneyBuff = 0
  player.basicInfo.maxHpBuff = 0
  player.calcAttri()
  player.fightAttri.hp = player.fightAttri.maxHp
  player.basicInfo.stamina = player.fightAttri.maxStamina
  player.basicInfo.lattice = 0
  player.basicInfo.secretMap = 0
  player.basicInfo.mapIndex = 1
  player.basicInfo.secretMapId = 0
  player.basicInfo.devilCaveIndex = 0
  next({
    error: 0,
    basicInfo: player.basicInfo
  })
})

//打孔
route.set('punch', function(player, msg, next) {
  let part = msg.part
  let equipment = player.equipments[part]
  if (!equipment) {
    next(1)
    return
  }

  if (equipment.solt.length !== 0) {
    next(2)
    return
  }
  let punchConfig = templateConfig.total[290040][equipment.quality]
    //查看是否有打孔器
  let num = player.bag.getTotalNumByItemId(punchConfig.needProp[0])
  if (num <= punchConfig.needProp[1]) {
    next(3)
    return
  }
  if (punchConfig.needMoney1) {
    if (player.basicInfo.money < punchConfig.needMoney1 * equipment.lvl) {
      next(4)
      return
    }
    player.basicInfo.money -= punchConfig.needMoney1 * equipment.lvl
  }

  if (punchConfig.needGold1) {
    if (player.basicInfo.gold < punchConfig.needGold1 * equipment.lvl) {
      next(5)
      return
    }
    player.basicInfo.gold -= punchConfig.needGold1 * equipment.lvl
  }
  //扣除道具
  player.bag.removeItemByItemId(240003, 1)

  equipment.solt[0] = 0
  next({
    error: 0
  })
})

//镶嵌宝石
route.set('setGem', function(player, msg, next) {
  let pos = msg.pos
  let part = msg.part
  let item = player.bag.items[pos]
  if (!item) {
    next(1)
    return
  }
  pos = parseInt(pos)
  let itemTemplateId = item.templateId
  if (Math.floor(itemTemplateId / 10000) !== 25) {
    next(2)
    return
  }

  let equipment = player.equipments[part]
  if (!equipment || equipment.solt.length !== 1 || equipment.solt[0] !== 0) {
    next(3)
    return
  }
  let config = templateConfig.total[290040][equipment.quality]
  if (config.needMoney2) {
    if (player.basicInfo.money < config.needMoney2 * equipment.lvl) {
      next(4)
      return
    }
    player.basicInfo.money -= config.needMoney2 * equipment.lvl
  }

  if (config.needGold2) {
    if (player.basicInfo.gold < config.needGold2 * equipment.lvl) {
      next(5)
      return
    }
    player.basicInfo.gold -= config.needGold2 * equipment.lvl
  }

  //扣除道具
  player.bag.removeSomeItemByPosition(pos, 1)
  equipment.solt[0] = itemTemplateId
  player.calcAttri()
  next({
    error: 0
  })
})

//移除宝石
route.set('removeGam', function(player, msg, next) {
  let part = msg.part

  //判断背包是否有空
  if (player.bag.emptySize === 0) {
    next(1)
    return
  }

  let equipment = player.equipments[part]
  if (!equipment || equipment.solt.length !== 1 || equipment.solt[0] === 0) {
    next(2)
    return
  }
  let config = templateConfig.total[290040][equipment.quality]
  if (config.needMoney3) {
    if (player.basicInfo.money < config.needMoney3 * equipment.lvl) {
      next(4)
      return
    }
    player.basicInfo.money -= config.needMoney3 * equipment.lvl
  }

  if (config.needGold3) {
    if (player.basicInfo.gold < config.needGold3 * equipment.lvl) {
      next(5)
      return
    }
    player.basicInfo.gold -= config.needGold3 * equipment.lvl
  }

  let itemTemplateId = equipment.solt[0]
    //添加道具
  let item = templateConfig.total[itemTemplateId].getItemComponent()
  player.bag.addItem(item)

  equipment.solt[0] = 0
  player.calcAttri()
  next({
    error: 0
  })
})

//打技能书
route.set('setSkillBook', function(player, msg, next) {
  let pos = msg.pos
  let soul = player.equipments.soul
  if (!soul) {
    next(1)
    return
  }
  pos = parseInt(pos)
  let item = player.bag.items[pos]
  if (!item) {
    next(2)
    return
  }
  let itemInfo = templateConfig.prop[item.templateId]
  if (Math.floor(item.templateId / 10000) != 22) { //是不是附魂书
    next(3)
    return
  }
  let skills = soul.skills

  //判断是否有一样的技能
  for (let i in skills) {
    if (skills[i] === itemInfo.skillId) {
      next(4)
      return
    }

    if (itemInfo.suffixSkill && itemInfo.suffixSkill === skills[i]) {
      next(4)
      return
    }
  }

  let result = skillHandle.setSkillBook(skills, itemInfo)
  player.bag.removeItemByPosition(pos)
  player.calcAttri()
  next({
    error: 0,
    result: result
  })
})

//使用补给栏
route.set('useCureBar', function(player, msg, next) {
  let mapIndex = player.basicInfo.mapIndex
  if (!(mapIndex !== 3 || mapIndex !== 4 || mapIndex !== 5)) {
    next(1)
    return
  }

  if (player.fightAttri.hp === player.fightAttri.maxHp) {
    next(2)
    return
  }

  if (player.fightAttri.hp <= 0) {
    next(3)
    return
  }

  let cureBarItem = player.cureBar
  if (!cureBarItem) {
    next(4)
    return
  }

  player.fightAttri.hp = player.fightAttri.maxHp

  cureBarItem.stack -= 1
  if (cureBarItem.stack === 0) {
    player.cureBar = null
  }

  next({
    error: 0
  })
})

//扩展背包
route.set('addBagSize', function(player, msg, next) {
  let bagConfig = templateConfig.other[290030]
  if (player.bag.size < (bagConfig.free + bagConfig.money)) {
    let size = player.bag.size - bagConfig.free
    if(size < 0){
      size = 0
    }
    let config = templateConfig.other[290031]
    let needMoney = config.needMoney[0] * size * 2 + config.needMoney[1]
    let propId = config.prop[0]
    let propNum = config.prop[1] * size + config.prop[2]
    if (player.bag.getTotalNumByItemId(propId) < propNum) {
      next(1)
      return
    }
    if (player.basicInfo.money < needMoney) {
      next(2)
      return
    }
    player.bag.initPackag()
    player.bag.removeItemByItemId(propId, propNum)
    player.basicInfo.money -= needMoney
    player.bag.size += 1
    player.bag.emptySize += 1
    player.bag.initPackag()
    next({
      error: 0
    })
    return
  }

  if (player.bag.size < (bagConfig.free + bagConfig.money + bagConfig.gold)) {
    let size = player.bag.size - bagConfig.free - bagConfig.money
    if(size < 0){
      size = 0
    }
    let config = templateConfig.other[290032]
    let needGold = config.needGold[0] * size + config.needGold[1]
    let propId = config.prop[0]
    let propNum = config.prop[1] * size + config.prop[2]
    if (player.bag.getTotalNumByItemId(propId) < propNum) {
      next(3)
      return
    }
    if (player.basicInfo.gold < needGold) {
      next(4)
      return
    }
    player.bag.initPackag()
    player.bag.removeItemByItemId(propId, propNum)
    player.basicInfo.gold -= needGold
    player.bag.size += 1
    player.bag.emptySize += 1
    player.bag.initPackag()
    next({
      error: 0
    })
    return
  }
  next(5)
})

//整理背包
route.set('arrange', function(player, msg, next) {
  player.bag.arrangePackage()
  next({
    error: 0
  })
})

//使用道具
route.set('useProp', function(player, msg, next) {
  let pos = msg.pos
  let item = player.bag.items[pos]
  if (!item) {
    next(1)
    return
  }

  let itemConfig = templateConfig.total[item.templateId]
  if (!itemConfig.propType) {
    next(2)
    return
  }

  if (player.bag.emptySize < itemConfig.getNum + 1) {
    next(3)
    return
  }

  switch (itemConfig.propType) {
    case 1:
      player.bag.removeSomeItemByPosition(pos, 1)
      var min = itemConfig.getMoney[0]
      var max = itemConfig.getMoney[1]
      var getMoney = Math.floor(Math.random() * (max - min) + min)
      player.basicInfo.money += getMoney
      min = itemConfig.getGold[0]
      max = itemConfig.getGold[1]
      var getGold = Math.floor(Math.random() * (max - min) + min)
      player.basicInfo.gold += getGold
      var props = utils.getRandomArray(itemConfig.getNum, itemConfig.getProps)
      for (var i = 0; i < props.length; i++) {
        var prop = props[i]
        var propId = prop[0]
        var propNum = prop[1]
        var itemComponent = templateConfig.total[propId].getItemComponent(propNum, 1)
        player.bag.addItem(itemComponent)
      }
      var getProp = itemConfig.getProp
      if (getProp) {
        var propId = getProp[0]
        min = itemConfig.getProp[1]
        max = itemConfig.getProp[2]
        var num = Math.floor(Math.random() * (max - min) + min)
        var itemComponent = templateConfig.total[propId].getItemComponent(num)
        player.bag.addItem(itemComponent)
        props.push([propId, num])
      }
      next({
        error: 0,
        getMoney: getMoney,
        getGold: getGold,
        props: props
      })
      return
      break
  }
  next(0)
})

//竞技场挑战玩家
route.set('arenaChallenge', function(player, msg, next) {
  let index = parseInt(msg.index)
  if (player.basicInfo.lvl < 4) {
    next(3)
    return
  }
  if (player.basicInfo.arenaTimes === 0 && player.bag.getTotalNumByItemId(240041) === 0) {
    next(1)
    return
  }

  let fightMsg = arenaHandle.challengePlayer(player, index)
  if (fightMsg !== -1) {
    if (player.basicInfo.arenaTimes > 0) {
      player.basicInfo.arenaTimes -= 1
    } else {
      player.bag.removeItemByItemId(240041, 1)
    }
    next({
      error: 0,
      fightMsg: fightMsg
    })
  } else {
    next(2)
    return
  }
})

//查看竞技场信息
route.set('getArenaMyInfo', function(player, msg, next) {
  if (player.basicInfo.lvl < 4) {
    next(3)
    return
  }
  let info = arenaHandle.getMyInfo(player)
  next({
    error: 0,
    arenaTimes: player.basicInfo.arenaTimes,
    info: info
  })
})

//查看竞技场信息
route.set('getArenaInfo', function(player, msg, next) {
  if (player.basicInfo.lvl < 4) {
    next(3)
    return
  }
  let info = arenaHandle.getArenaInfo(player)
  next({
    error: 0,
    info: info
  })
})

//出售物品到交易所
route.set('sellToTrade', function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  let pos = msg.pos
  let item = player.bag.items[pos]

  let re = /^[1-9][0-9]*$/
  if (!re.test(msg.num) || !re.test(msg.sellGold)) {
    next(1)
    return
  }

  let num = parseInt(msg.num)
  let sellGold = parseInt(msg.sellGold)

  if (!item || item.bind === 0) {
    next(2)
    return
  }

  if (item.stack < num) {
    next(3)
    return
  }
  let itemConfig = templateConfig.total[item.templateId]
  let t = {
    playerId: player._id,
    itemId: item.templateId,
    pName: player.name,
    itemNum: num,
    sellGold: sellGold,
    sellType: itemConfig.sellType
  }
  tradeDao.itemCount(player._id, function(err, res) {
    if (err || res >= 8) {
      next(4)
      return
    }
    tradeDao.newAndSave(t, function(err, res) {
      player.bag.removeSomeItemByPosition(pos, num) //扣除物品
      next(0)
      return
    })
  })
})

//获取交易所信息
route.set("getTradeInfo", function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  let re = /^[0-9]*$/
  if (!re.test(msg.sellType) || !re.test(msg.page)) {
    next(1)
    return
  }
  let sellType = parseInt(msg.sellType)
  let page = parseInt(msg.page)
  let query
  if (sellType === 0) {
    query = {}
  } else {
    query = {
      sellType: sellType
    }
  }

  tradeDao.getItemsByQuerys(query, page, 8, function(err, res) {
    next({
      error: 0,
      trades: res,
      isFirst: page === 0,
      isLast: res.length < 9
    })
  })
})

//获取我的交易所信息
route.set("getMyTradeInfo", function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  let query = {
    pId: player._id
  }
  tradeDao.getItemsByQuerys(query, 0, 10, function(err, res) {
    next({
      error: 0,
      trades: res
    })
  })
})

//购买交易所物品
route.set("bugTrade", function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  let re = /^[0-9]*$/
  if (!re.test(msg.tradeId)) {
    next(1)
    return
  }
  var tradeId = parseInt(msg.tradeId)
  tradeDao.getItemByQuery({
    _id: tradeId
  }, function(err, res) {
    if (err || !res || res.length === 0) {
      next(2)
      return
    }

    if (res.pId === player._id) {
      next(3)
      return
    }

    let totalGold = res.sellGold * res.itemNum
    if (player.basicInfo.gold < totalGold) {
      next(4)
      return
    }

    tradeDao.removeItemByQuery({
      _id: tradeId
    }, function() {
      player.basicInfo.gold -= totalGold
      let title = '交易所信息'
      let content = '你成功购买了交易所的物品'
      let items = [
        [res.itemId, res.itemNum, 1]
      ]
      mailDao.newAndSave(player._id, title, content, items, 0, 0, function(err) {})
      content = '你的物品已成功出售'
      mailDao.newAndSave(res.pId, title, content, [], 0, totalGold, function(err) {})
      next(0)
      return
    })
  })
})

//取消上架物品
route.set("cancelSell", function(player, msg, next) {
  if (player.basicInfo.lvl < 3) {
    next(5)
    return
  }
  let re = /^[0-9]*$/
  if (!re.test(msg.tradeId)) {
    next(1)
    return
  }

  var tradeId = parseInt(msg.tradeId)

  tradeDao.getItemByQuery({
    _id: tradeId,
    pId: player._id
  }, function(err, res) {
    if (err || res.length === 0) {
      next(2)
      return
    }
    tradeDao.removeItemByQuery({
      _id: tradeId,
      pId: player._id
    }, function() {
      let title = '交易所信息'
      let content = '你下架了交易所的物品'
      let items = [
        [res.itemId, res.itemNum, 1]
      ]
      mailDao.newAndSave(player._id, title, content, items, 0, 0, function(err) {})
      next(0)
      return
    })
  })
})

//保存角色后退出服务器
route.set('savePlayerAndClose', function(player, msg, next) {
  playerDao.savePlayerById(player._id, player, function(err, ret) {
    let error = err ? 1 : 0
    playerSessionMgr.delPlayer(player._id)
    next({
      error: error,
      ret: ret
    })
  })
})

//保存角色后退出服务器
route.set('savePlayer', function(player, msg, next) {
  playerDao.savePlayerById(player._id, player, function(err, ret) {
    let error = err ? 1 : 0
    next({
      error: error,
      ret: ret
    })
  })
})

//获取基本属性
route.set('getBasicInfo', function(player, msg, next) {
  next({
    error: 0,
    basicInfo: player.basicInfo
  })
})


//获取战斗属性
route.set('getFightAttri', function(player, msg, next) {
  next({
    error: 0,
    fightAttri: player.fightAttri
  })
})

//获取背包信息
route.set('getBagInfo', function(player, msg, next) {
  next({
    error: 0,
    bag: player.bag.getInfo(),
    money: player.basicInfo.money,
    gold: player.basicInfo.gold
  })
})

//获取冒险信息栏信息
route.set('getAdvInfo', function(player, msg, next) {
  next({
    error: 0,
    hp: player.fightAttri.hp,
    maxHp: player.fightAttri.maxHp,
    lucky: player.fightAttri.lucky,
    luckyBuff: player.basicInfo.luckyBuff,
    stamina: player.basicInfo.stamina,
    advBagLen: player.adventureBag.length,
    cureBarLen: player.cureBar ? player.cureBar.stack : 0,
  })
})


//获取装备信息
route.set('getEquipments', function(player, msg, next) {
  next({
    error: 0,
    equipments: player.equipments
  })
})

//获取冒险背包
route.set('getAdventureBag', function(player, msg, next) {
  next({
    error: 0,
    adventureBag: player.adventureBag
  })
})

//获取玩家信息
route.set('getPlayer', function(player, msg, next) {
  next({
    error: 0,
    basicInfo: player.basicInfo,
    fightAttri: player.fightAttri
  })
})

//免费领取补给品
route.set('takeAlms', function(player, msg, next) {
  if (player.basicInfo.emptySize <= 0) {
    next(1)
    return
  }

  if (player.basicInfo.takeAlmsTimes <= 0) {
    next(2)
    return
  }
  if (player.bag.getTotalNumByItemId(240101) >= 3) {
    next(3)
    return
  }
  var itemComponent = templateConfig.total[240101].getItemComponent(3)
  player.bag.addItem(itemComponent)
  player.basicInfo.takeAlmsTimes -= 1
  next({
    error: 0,
    num: 3,
    propId: 240101
  })
})
